package com.wontube.core.conf;

import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.google.gson.Gson;
import com.wontube.client.extension.utils.FileUtils;

/**
 * @author yuechao 
 * 
 * 数据源配置信息
 * 
 */
public class Datasource implements Serializable {
	private static final long serialVersionUID = 6794354063936377986L;

	private static final Logger logger = LoggerFactory.getLogger(Datasource.class);
	private String dataPath;
	
	private static Datasource defaultDatasource = new Datasource();

	/**
	 * 数据库连接配置
	 * 
	 */
	private List<Database> databases = new ArrayList<Database>();

	public static Datasource getDefaultDataSource() {
		return defaultDatasource;
	}
	
	/**
	 * 获取指定的数据库连接配置
	 * 
	 * @param name
	 * @return
	 */
	public Database get(String name) {
		for (Database obj : this.databases) {
			if (name.equalsIgnoreCase(obj.getName())) {
				return obj;
			}
		}

		return null;
	}

	/**
	 * 数据源
	 * 
	 * @return
	 */
	public List<Database> getDatabases() {
		return this.databases;
	}
	
	/**
	 * 数据存储位置
	 * 
	 * @return
	 */
	public String getDataPath() {
		return this.dataPath;
	}
	
	/**
	 * 设置数据存储位置
	 * 
	 * @param value
	 */
	public void setDataPath(String value) {
		this.dataPath = value;
	}

	/**
	 * 装载数据源配置信息
	 * 
	 * @return
	 */
	public static Datasource load(File file) {
		String json = "";
		try {
			json = FileUtils.readAllText(file);
		} catch (IOException ex) {
			logger.error(ex.toString());
		}
		
		if ("".equals(json)) {
			return new Datasource();
		}
	
		Gson gson = new Gson();
		Datasource datasource = gson.fromJson(json, Datasource.class);
		defaultDatasource = datasource;
		
		return datasource;
	}
}
